/*
 *    Copyright 2009-2022 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.AAMyDemo;

import org.apache.ibatis.datasource.unpooled.UnpooledDataSource;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.Transaction;
import org.apache.ibatis.transaction.jdbc.JdbcTransaction;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;

/**
 * @Author yangSen
 * @Date 2022年03月16日 10:52
 */
public class MyBaseTest {


  /**
   * 配置文件路径
   */
  public static final String RESOURCE_PATH = "org/apache/ibatis/AAMyDemo/config/mybatis-config.xml";
  private static final String DRIVER = "org.hsqldb.jdbcDriver";
  private static final String URL = "jdbc:mysql://47.102.20.116:3306/mybatis_use";
  private static final String USERNAME = "root";
  private static final String PASSWORD = "root";


  /**
   * 返回数据库源
   *
   * @return 数据库源
   *
   * @throws Exception
   */
  public static DataSource getDataSource() {
    UnpooledDataSource ds = new UnpooledDataSource();
    ds.setDriver(DRIVER);
    ds.setUrl(URL);
    ds.setUsername(USERNAME);
    ds.setPassword(PASSWORD);
    return ds;
  }

  /**
   * 返回一个数据库链接对象
   *
   * @return
   *
   * @throws Exception
   */
  public static Connection getConnection() throws Exception {
    return getDataSource().getConnection();
  }


  /**
   * 返回配置对象
   *
   * @param path xml文件路径
   * @return
   */
  public static Configuration getConfiguration(String path) throws IOException {
    InputStream inputStream = Resources.getResourceAsStream(path);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    return sqlSessionFactory.getConfiguration();
  }

  /**
   * 返回事务对象
   *
   * @return
   *
   * @throws Exception
   */
  public static Transaction getTransaction() throws Exception {
    return new JdbcTransaction(getConnection());
  }


}
